package cn.mesmile.thread;

import cn.hutool.core.thread.ThreadFactoryBuilder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author zb
 * @date 2021/3/23 22:29
 * @Description
 */
public class AlternatePrinting {

    public volatile static boolean whetherToPrint =  false;

    public static final Object lock = new Object();

    public static int count = 0;

    public static List<Integer> data  = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7,8,9,10));

    public static void main(String[] args) {

        Runnable a = new Runnable(){
            @Override
            public void run() {
                while (count < 10){
                    try {
                        if(!whetherToPrint) {
                            lock.wait();
                        }
                        System.out.println(Thread.currentThread().getName() +data.get(count));
                        ++count;
                        whetherToPrint = false;
                        // 唤醒 偶数线程
                        lock.notify();
                    }  catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Runnable b = new Runnable() {
            @Override
            public void run() {
                while (count < 10){
                    try {
                        if(whetherToPrint) {
                            lock.wait();
                        }
                        System.out.println(Thread.currentThread().getName() +data.get(count));
                        ++count;
                        whetherToPrint = true;
                        // 唤醒 偶数线程
                        lock.notify();
                    }  catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Thread threadA = new Thread(a);
        Thread threadB = new Thread(b);
        threadA.setName("threadA: ");
        threadB.setName("threadB: ");
        threadA.start();
        threadB.start();

    }






}
